// import React from 'react'
import { useNavigate } from "react-router-dom";

import { Form, TextArea, Button } from "antd-mobile";

import { NavBar } from "antd-mobile";
import {
  addAddressAPI,
  loadAddressAPI,
  delDIZHIAPI,
  loadDANTIAOAPI,
  editAPI,
} from "../services/user";
import { useEffect, useState } from "react";
import { AddOutline } from "antd-mobile-icons";

function Address() {
  const [myFrom] = Form.useForm();
  const nav = useNavigate();
  const back = () => nav(-1);
  const [list, setList] = useState([]);
  const [isShow, setIsShow] = useState("none");
  const [currentId, setCurrentId] = useState("");
  useEffect(() => {
    loadAddressAPI().then((res) => {
      console.log(res);
      setList(res.data);
    });
  }, []);
  return (
    <div style={{ padding: "16px" }}>
      <NavBar
        back="返回"
        onBack={back}
        right={<AddOutline onClick={() => setIsShow("block")} />}
      ></NavBar>
      <div>
        <h1>我的地址</h1>
        {list.map((item) => (
          <div key={item.id}>
            <p>{item.address}</p>
            <Button
              onClick={async () => {
                setIsShow("block");
                const info = await loadDANTIAOAPI(item.id);
                myFrom.setFieldsValue(info.data);
                setCurrentId(item.id);
              }}
            >
              修改
            </Button>
            <Button
              onClick={() => {
                delDIZHIAPI(item.id);
                history.go(0);
              }}
            >
              删除
            </Button>
            <hr></hr>
          </div>
        ))}
      </div>
      <div style={{ display: isShow }}>
        <Form
          form={myFrom}
          layout="horizontal"
          footer={
            <Button block type="submit" color="primary" size="large">
              新增地址
            </Button>
          }
          onFinish={(v) => {
            if (currentId) {
              editAPI(currentId, v);
              setIsShow("none");
              history.go(0);
            } else {
              addAddressAPI(v);
              setIsShow("none");
              history.go(0);
            }
          }}
        >
          <Form.Item name="address" label="地址" help="详情地址">
            <TextArea placeholder="请输入地址" maxLength={100} rows={4} />
          </Form.Item>
        </Form>
      </div>
    </div>
  );
}

export default Address;
